import { Drawer, Form, Input, Flex, Button, Space, message } from "antd";
import { InputType, SButton, SForm } from "@cnjingx/antd-components";
import { useRequest } from "@/hooks/useRequest.js";
import { fetchChangePwd } from "@/api/modules/user.js";
import { encrypt, msg } from "@/utils/util.js";
import { isEmpty } from "wsp-toolkit";
import { checkPwd } from "@/utils/validator";
export function ChangePwdDrawer({ open, onClose }) {
  const [form] = Form.useForm();

  const formItems = [
    {
      label: "旧密码",
      name: "previousPassword",
      required: true,
      inputType: InputType.password,
    },
    {
      label: "新密码",
      name: "currentPassword",
      required: true,
      inputType: InputType.password,
      rules: [
        {
          validator: (rule, value) => {
            if (isEmpty(value)) return Promise.resolve();
            if (value === form.getFieldValue("previousPassword")) {
              return Promise.reject(new Error("新旧密码不能相同"));
            }
            const [ok, msg] = checkPwd(value);
            if (ok) return Promise.resolve();
            return Promise.reject(new Error(msg));
          },
        },
      ],
    },
    {
      label: "确认新密码",
      name: "reCurrentPassword",
      required: true,
      inputType: InputType.password,
      rules: [
        {
          validator: (rule, value) => {
            if (isEmpty(value)) return Promise.resolve();
            if (value !== form.getFieldValue("currentPassword")) {
              return Promise.reject(
                new Error("输入的确认新密码应与新密码相同"),
              );
            }
            return Promise.resolve();
          },
        },
      ],
    },
  ];
  const { loading, run } = useRequest(fetchChangePwd, {
    manual: true,
    onSuccess: () => {
      message.success("修改密码成功");
      handleClose();
    },
  });
  async function handleSubmit() {
    const data = await form.validateFields();
    run({
      previousPassword: encrypt(data.previousPassword),
      currentPassword: encrypt(data.currentPassword),
    });
  }
  function handleClose() {
    onClose();
    form.resetFields();
  }

  return (
    <Drawer
      title={`新增用户`}
      placement="right"
      size={"large"}
      onClose={handleClose}
      open={open}
      maskClosable={false}
      footer={
        <div className={"flex"} style={{ justifyContent: "flex-end" }}>
          <Space>
            <SButton onClick={handleClose}>取消</SButton>
            <SButton type="primary" onClick={handleSubmit} loading={loading}>
              确认
            </SButton>
          </Space>
        </div>
      }
    >
      <SForm
        layout={"vertical"}
        formItems={formItems}
        columnRepeat={1}
        form={form}
      ></SForm>
    </Drawer>
  );
}
